﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuanLyNhaThuoc.Models;
using QuanLyNhaThuoc.HelperClass;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Data.Objects;
using System.Web.UI;
using System.Data.Common;

namespace QuanLyNhaThuoc.Controllers {
    public class TransactionController : Controller {
        #region Check permission
        protected override void OnActionExecuting(ActionExecutingContext filterContext) {
            #region Check session login
            if (HttpContext.Session["USERID"] == null) {
                Response.Redirect("~/Account/LogIn");
            }
            #endregion

            #region Check function permission
            string controller = RouteData.Values["controller"].ToString();
            string action = RouteData.Values["action"].ToString();

            var query = PMOEn.CheckFunctionPermission(Session["USERID"].ToString(), controller, action).ToList();
            if (query.Count != 0) {
                ViewBag.Title = query[0].Title;
            } else {
                Response.Redirect("~/Error/Denied");
            }
            #endregion

            base.OnActionExecuting(filterContext);
        }
        #endregion

        #region Khởi tạo

        PMOEntities PMOEn = new PMOEntities();

        [HttpGet]
        public JsonResult LoadStore(WarehouseModel wh_model) {
            // Load Store Pharmacy
            var List_Store = PMOEn.LoadStore("");

            List<SelectListItem> _listStore = new List<SelectListItem>();

            foreach (var item in List_Store) {
                _listStore.Add(new SelectListItem() {
                    Text = item.CorpName,
                    Value = item.CorpID.ToString()
                });
            }

            _listStore.Insert(0, new SelectListItem() { Value = "", Text = ConfigurationManager.AppSettings["SelectOne"].ToString() });
            wh_model.SelectedValue_Store = String.Empty;
            wh_model.ListStore = _listStore;

            return Json(_listStore, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadBranch(WarehouseModel wh_model) {
            // Load Store Pharmacy
            var List_Branch = PMOEn.LoadBranch(Session["BRANCHID"].ToString());

            List<SelectListItem> _listBranch = new List<SelectListItem>();

            foreach (var item in List_Branch) {
                _listBranch.Add(new SelectListItem() {
                    Text = item.BranchName,
                    Value = item.BranchID.ToString()
                });
            }

            if (Session["BRANCHID"] != null) {
                wh_model.SelectedValue_Branch = Session["BRANCHID"].ToString();
            } else {
                _listBranch.Insert(0, new SelectListItem() { Value = "", Text = ConfigurationManager.AppSettings["SelectOne"].ToString() });
            }
            wh_model.ListBranch = _listBranch;

            return Json(_listBranch, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadDrug(WarehouseModel wh_model) {
            // Load Drug     
            var List_Drug = PMOEn.LoadDrug();

            List<SelectListItem> _listDrug = new List<SelectListItem>();

            foreach (var item in List_Drug) {
                _listDrug.Add(new SelectListItem() {
                    Text = item.ProductTypeName,
                    Value = item.ProductTypeID.ToString()
                });
            }

            _listDrug.Insert(0, new SelectListItem() { Value = "", Text = ConfigurationManager.AppSettings["SelectOne"].ToString() });
            wh_model.SelectedValue_Drug = String.Empty;
            wh_model.ListDrug = _listDrug;

            return Json(_listDrug, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadUnit(WarehouseModel wh_model) {
            // Load Unit

            var List_Unit = PMOEn.LoadUnit();

            List<SelectListItem> _listUnit = new List<SelectListItem>();

            foreach (var item in List_Unit) {
                _listUnit.Add(new SelectListItem() {
                    Text = item.UnitName,
                    Value = item.UnitID.ToString()
                });
            }

            _listUnit.Insert(0, new SelectListItem() { Value = "", Text = ConfigurationManager.AppSettings["SelectOne"].ToString() });
            wh_model.SelectedValue_Unit = String.Empty;
            wh_model.ListUnit = _listUnit;

            return Json(_listUnit, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadCurrency(WarehouseModel wh_model) {
            //Load Currency

            var List_CCYID = PMOEn.LoadAllCodeByName(SYSVAR.CCYID, String.Empty);

            List<SelectListItem> _listCurrency = new List<SelectListItem>();

            foreach (var item in List_CCYID) {
                _listCurrency.Add(new SelectListItem() {
                    Text = item.Content,
                    Value = item.Value.ToString()
                });
            }

            _listCurrency.Insert(0, new SelectListItem() { Value = "", Text = ConfigurationManager.AppSettings["SelectOne"].ToString() });
            wh_model.SelectedValue_Currency = String.Empty;
            wh_model.ListCurrency = _listCurrency;

            return Json(_listCurrency, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadStatus(WarehouseModel wh_model) {
            //Load Status

            var List_Status = PMOEn.LoadAllCodeByName(SYSVAR.STATUS, ConfigurationManager.AppSettings["InUse"].ToString());

            List<SelectListItem> _listStatus = new List<SelectListItem>();

            foreach (var item in List_Status) {
                _listStatus.Add(new SelectListItem() {
                    Text = item.Content,
                    Value = item.Value.ToString()
                });
            }

            //_listStatus.Insert(0, new SelectListItem() { Value = "", Text = ConfigurationManager.AppSettings["SelectOne"].ToString() });
            wh_model.SelectedValue_Status = String.Empty;
            wh_model.ListStatus = _listStatus;

            return Json(_listStatus, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadSupplier(WarehouseModel wh_model) {
            //Load Status

            var List_Supplier = PMOEn.LoadSupplier();

            List<SelectListItem> _listSupplier = new List<SelectListItem>();

            foreach (var item in List_Supplier) {
                _listSupplier.Add(new SelectListItem() {
                    Text = item.SupplierName,
                    Value = item.SupplierID.ToString()
                });
            }

            _listSupplier.Insert(0, new SelectListItem() { Value = "", Text = ConfigurationManager.AppSettings["SelectOne"].ToString() });
            wh_model.SelectedValue_Supplier = String.Empty;
            wh_model.ListSupplier = _listSupplier;

            return Json(_listSupplier, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Danh sách phiếu nhập kho

        private WarehouseModel BindData(int page, int pageSize, string KeySearch, string ValueSearch) {
            System.Data.Objects.ObjectParameter output = new System.Data.Objects.ObjectParameter("TOTAL", typeof(int));

            WarehouseModel whMo = new WarehouseModel();

            if (KeySearch != null) {
                whMo.IWareHouse = PMOEn.GetWarehouse(Session["BRANCHID"].ToString(), Session["CORPID"].ToString(), output, page, pageSize, KeySearch, ValueSearch).ToList();
            } else {
                whMo.IWareHouse = PMOEn.GetWarehouse(Session["BRANCHID"].ToString(), Session["CORPID"].ToString(), output, page, pageSize, "", "").ToList();
            }


            var result = PMOEn.LoadAllCodeByName(SYSVAR.SEARCH, "").ToList();

            List<SelectListItem> list = new List<SelectListItem>();
            foreach (var item in result) {
                SelectListItem sl = new SelectListItem();
                sl.Text = item.Content;
                sl.Value = item.Value;

                if (KeySearch != null) {
                    if (item.Value == KeySearch) {
                        sl.Selected = true;
                    }
                }

                list.Add(sl);
            }

            whMo.ListSearch = list;
            var model = new PagingModel() {
                CurrentPageIndex = page,
                PageSize = pageSize
            };

            // Determine the total number of products being paged through (needed to compute PageCount)
            model.TotalRecordCount = int.Parse(output.Value.ToString());

            whMo.paging = model;

            return whMo;
        }

        public ActionResult SearchWareHouse(FormCollection frm, int Page = 1, int PageSize = 15) {
            try {
                WarehouseModel Wh_Model = new WarehouseModel();
                Wh_Model = BindData(Page, PageSize, frm[0], frm[1]);
                return View(Wh_Model);
            } catch (Exception ex) {
                Log.LogError(ex);
                return RedirectToAction("Index", "Error");
            }
        }

        public ActionResult Warehouse(int Page = 1, int PageSize = 15) {
            try {
                WarehouseModel Wh_Model = new WarehouseModel();
                Wh_Model = BindData(Page, PageSize, null, null);

                return View(Wh_Model);
            } catch (Exception ex) {
                Log.LogError(ex);
                return RedirectToAction("Index", "Error");
            }
        }
        #endregion

        #region Nhập kho

        [HttpGet]
        public ActionResult Import() {
            try {
                #region Load Dropdownlist
                WarehouseModel wh_model = new WarehouseModel();
                LoadStore(wh_model);
                LoadBranch(wh_model);
                LoadUnit(wh_model);
                LoadDrug(wh_model);
                LoadCurrency(wh_model);
                LoadSupplier(wh_model);
                LoadBranch(wh_model);
                LoadStatus(wh_model);
                #endregion
                return View(wh_model);
            } catch (Exception ex) {
                Log.LogError(ex);
                return View("Error500");
            }
        }

        [HttpPost]
        public JsonResult Warehouse_Creating(string jsonData, string productCode) {
            try {
                List<GetListWarehouseByIBID_Result> ls_wh_model = new List<GetListWarehouseByIBID_Result>();
                GetListWarehouseByIBID_Result model = new GetListWarehouseByIBID_Result();
                JavaScriptSerializer jss = new JavaScriptSerializer();
                model = jss.Deserialize<GetListWarehouseByIBID_Result>(jsonData.Replace(".", String.Empty));
                int _status = 0;
                if (Session["data"] != null) {
                    ls_wh_model = (List<GetListWarehouseByIBID_Result>)Session["data"];
                    if (ls_wh_model.Where(x => x.ProductCode.Trim() == productCode.Trim()).ToList().Count() != 0) {
                        _status = 2; // Trùng ProcudeCode
                    } else {
                        _status = 0; // Insert into List<Warehouse>
                        ls_wh_model.Add(model);
                    }
                } else {
                    _status = 0; // Insert into List<Warehouse>
                    ls_wh_model.Add(model);
                }
                int id = 1;
                foreach (var item in ls_wh_model) {
                    item.ID = id;
                    id++;
                }
                Session["data"] = ls_wh_model;
                return Json(new { status = _status, data = ls_wh_model });

            } catch (Exception ex) {
                Log.LogError(ex);
                return Json(new { status = 1 }); // Error
            }
        }

        [HttpPost]
        public JsonResult Warehouse_Removing(string jsonData) {
            try {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                List<GetListWarehouseByIBID_Result> ls_wh_model = new List<GetListWarehouseByIBID_Result>();
                var arr = jss.Deserialize<string[]>(jsonData);

                ls_wh_model = (List<GetListWarehouseByIBID_Result>)Session["data"];
                foreach (var item in arr) {
                    ls_wh_model.RemoveAll((x) => x.ProductCode.Trim() == item.Trim());
                }
                int id = 1;
                foreach (var item in ls_wh_model) {
                    item.ID = id;
                    id++;
                }
                Session["data"] = ls_wh_model;
                return Json(new { status = 0, data = ls_wh_model });
            } catch (Exception ex) {
                Log.LogError(ex);
                return Json(new { status = 1 });
            }
        }

        [HttpPost]
        public JsonResult Warehouse_Saving() {
            PMOEn.Connection.Open();
            var data = new Object();
            var Transaction = PMOEn.Connection.BeginTransaction();

            try {
                var jss = new JavaScriptSerializer();

                //Delete data
                int resultDelete = 0;

                if (Session["ID"] != null) {
                    resultDelete = PMOEn.RemoveWarehouseFromList(Session["ID"].ToString().Trim()).FirstOrDefault().Result;
                }

                // Save data
                List<GetListWarehouseByIBID_Result> ls_wh_model = new List<GetListWarehouseByIBID_Result>();
                ls_wh_model = (List<GetListWarehouseByIBID_Result>)Session["data"];
                var ds = ls_wh_model;
                int resultInsert = 0;

                foreach (var item in ds) {
                    resultInsert = PMOEn.ImportWarehouse(item.IBNumber, Session["USERID"].ToString(), item.Deliverer, Session["BRANCHID"].ToString(),
                    Session["CORPID"].ToString(), item.Des_IB, item.ProductID.ToString(), item.ProductCode, item.ProductName, item.SelectedValue_Drug.ToString(), Int32.Parse(item.COUNT.ToString().Replace(".", String.Empty)), item.SelectedValue_Unit, item.Buy.ToString(),
                    item.CCYID, item.ExpireDate, item.SelectedValue_Status, item.Place, item.Des_WH).FirstOrDefault().Result;
                }
                // 0 - Success ; 1 - Error
                Session.Remove("data");
                Session.Remove("ID");
                Transaction.Commit();
                return Json(new { status = resultDelete + resultInsert, data = ls_wh_model });
            } catch (Exception ex) {
                Transaction.Rollback();
                Log.LogError(ex);
                return Json(new { status = 1 });
            } finally {
                PMOEn.Connection.Dispose();
                PMOEn.Connection.Close();
            }
        }

        [HttpPost]
        public JsonResult Check_ProductCode(string pCode) {
            try {
                var iResult = PMOEn.CheckProductCode(pCode.Trim());
                return Json(new { status = iResult });
            } catch (Exception ex) {
                Log.LogError(ex);
                return Json(new { status = 0 });
            }
        }

        [HttpGet]
        public JsonResult AutoCompleteWareHouse(string searchTerm, int rows, string sord, string sidx, int page) {
            try {
                System.Data.Objects.ObjectParameter output = new System.Data.Objects.ObjectParameter("SL", typeof(int));
                var ls = PMOEn.Autocomplete_Warehouse(searchTerm, rows, sord, page, sidx, output, Session["CORPID"].ToString()).ToList();
                int Total = Int32.Parse(output.Value.ToString()) < rows ? 1 : (Int32.Parse(output.Value.ToString()) / rows + 1);
                foreach (var item in ls) {
                    item.Buy = Common.FormatMoneyDisplay(item.Buy.Split(' ')[0], item.CCYID) + ' ' + item.CCYID;
                    item.Sell = Common.FormatMoneyDisplay(item.Sell.Split(' ')[0], item.CCYID) + ' ' + item.CCYID;
                }
                return Json(new { page = "1", total = Total, records = "" + output.Value + "", rows = ls }, JsonRequestBehavior.AllowGet);
            } catch {
                return Json("500");
            }
        }
        #endregion

        #region Sửa phiếu

        public ActionResult Modify(string ID) {
            WarehouseModel wh_model = new WarehouseModel();
            wh_model.IBDetail = PMOEn.GetImportBillDetail(ID.Trim(), Session["BRANCHID"].ToString(), Session["CORPID"].ToString()).First();
            Session["data"] = PMOEn.GetListWarehouseByIBID(ID.Trim(), Session["BRANCHID"].ToString(), Session["CORPID"].ToString()).ToList();
            Session["ID"] = ID;
            #region Load Dropdownlist
            LoadStore(wh_model);
            LoadStatus(wh_model);
            LoadUnit(wh_model);
            LoadDrug(wh_model);
            LoadCurrency(wh_model);
            LoadSupplier(wh_model);
            LoadBranch(wh_model);
            #endregion
            return View(wh_model);
        }

        [HttpPost]
        public JsonResult GetInfoByWHID(string WH_ID) {
            var List = PMOEn.GetInfoByWh_ID(WH_ID.Trim());
            return Json(new { data = List });
        }

        [HttpPost]
        public JsonResult RemoveWhFromList(List<String> lsString, string WH_ID) {
            int result = 0;
            var jss = new JavaScriptSerializer();

            foreach (var item in lsString) {
                result = PMOEn.RemoveWarehouseFromList(item.Trim()).FirstOrDefault().Result;
            }
            var List = PMOEn.GetInfoByWh_ID(WH_ID.Trim());
            return Json(new { result = result, data = List });
        }

        #endregion

        #region Xóa phiếu
        [HttpPost]
        public JsonResult DeleteImportBill(List<string> lString, int page = 1, int pageSize = 15) {
            int Result = 0;
            PMOEn.Connection.Open();
            var Transaction = PMOEn.Connection.BeginTransaction();
            try {
                foreach (var item in lString) {
                    Result = PMOEn.DeleteImportBill(item.Trim()).FirstOrDefault().Result;
                }
                var List = BindData(page, pageSize, null, null);
                Transaction.Commit();
                return Json(new { status = Result, data = List });
            } catch (Exception ex) {
                Transaction.Rollback();
                Log.LogError(ex);
                return Json(new { status = 1 });
            } finally {
                PMOEn.Connection.Dispose();
                PMOEn.Connection.Close();
            }
        }
        #endregion

        #region Danh sách phiếu xuất kho

        private ExportModel BindDataBill(int page, int pageSize, string KeySearch, string ValueSearch) {
            System.Data.Objects.ObjectParameter output = new System.Data.Objects.ObjectParameter("TOTAL", typeof(int));

            ExportModel epMo = new ExportModel();

            if (KeySearch != null) {
                epMo.ListExportBill = PMOEn.GetExportBill(Session["CORPID"].ToString(), Session["BRANCHID"].ToString(), page, pageSize, KeySearch.ToString(), ValueSearch, output).ToList();
            } else {
                epMo.ListExportBill = PMOEn.GetExportBill(Session["CORPID"].ToString(), Session["BRANCHID"].ToString(), page, pageSize, "", "", output).ToList();
            }

            var result = PMOEn.LoadAllCodeByName(SYSVAR.SEARCH, "").ToList();

            List<SelectListItem> list = new List<SelectListItem>();
            foreach (var item in result) {
                SelectListItem sl = new SelectListItem();
                sl.Text = item.Content;
                sl.Value = item.Value;

                if (KeySearch != null) {
                    if (item.Value == KeySearch.ToString()) {
                        sl.Selected = true;
                    }
                }

                list.Add(sl);
            }

            epMo.ListKeySearch = list;
            var model = new PagingModel() {
                CurrentPageIndex = page,
                PageSize = pageSize
            };

            // Determine the total number of products being paged through (needed to compute PageCount)
            model.TotalRecordCount = int.Parse(output.Value.ToString());

            epMo.paging = model;

            return epMo;
        }

        public ActionResult Bill(int Page = 1, int PageSize = 15) {
            try {
                ExportModel epMo = new ExportModel();
                epMo = BindDataBill(Page, PageSize, null, null);
                return View(epMo);
            } catch (Exception ex) {
                Log.LogError(ex);
                return View("Error500");
            }
        }

        public ActionResult SearchBill(FormCollection frm, int Page = 1, int PageSize = 15) {
            try {
                ExportModel epMo = new ExportModel();
                epMo = BindDataBill(Page, PageSize, frm[0], frm[1]);
                return View(epMo);
            } catch (Exception ex) {
                Log.LogError(ex);
                return View("Error500");
            }
        }

        public ActionResult Sale() {
            return View();
        }

        public ActionResult Modify() {
            return View();
        }

        public JsonResult DeleteExportBill(List<string> ls_EBID, int Page = 1, int PageSize = 15) {
            PMOEn.Connection.Open();
            var Transaction = PMOEn.Connection.BeginTransaction();
            int Result = 0;
            try {
                foreach (var item in ls_EBID) {
                    Result = PMOEn.DeleteExportBill(item.Trim()).FirstOrDefault().Result;
                }
                var List = BindDataBill(Page, PageSize, null, null);
                Transaction.Commit();
                return Json(new { status = Result, data = List });
            } catch (Exception ex) {
                Transaction.Rollback();
                Log.LogError(ex);
                return Json(new { status = 1 });
            } finally {
                Transaction.Dispose();
                PMOEn.Connection.Close();
            }
        }

        [HttpGet]
        public JsonResult AutoCompleteBill(string searchTerm, int rows, string sord, string sidx, int page) {
            try {
                System.Data.Objects.ObjectParameter output = new System.Data.Objects.ObjectParameter("SL", typeof(int));
                var ls = PMOEn.Autocomplete_Bill(searchTerm, rows, sord, page, sidx, output, Session["CORPID"].ToString()).ToList();
                int Total = Int32.Parse(output.Value.ToString()) < rows ? 1 : (Int32.Parse(output.Value.ToString()) / rows + 1);
                return Json(new { page = "1", total = Total, records = "" + output.Value + "", rows = ls }, JsonRequestBehavior.AllowGet);
            } catch {
                return Json("500");
            }
        }

        #endregion

    }
}